#include <stdio.h>
#include <mqueue.h>
#include <unistd.h>
#include <pthread.h>

static const char *mq_name = "/test_mq";
static mqd_t mq;
// 第一个线程
void *thread1(void *argv)
{
    printf("thread1 \n");
    sleep(1);
    //接收消息
    char buf[256];
    ssize_t bit_receive= mq_receive(mq, buf, 256, NULL);
    if(bit_receive==-1){
        perror("mq_receive error");
        return NULL;
    }
    buf[bit_receive]='\0';
    printf("thread1 receive msg=%s \n",buf);
}

// 第二个线程
void *thread2(void *argv)
{
    printf("thread2 \n");
    sleep(1);
    //发送消息
    const char *msg = "hello, mq";
    if(mq_send(mq, msg, strlen(msg), 0)==-1){
        perror("mq_send error");
        return NULL;
    }
    printf("thread2 send msg=%s \n",msg);
    return NULL;
}
int main(int argc, char const *argv[])
{
    //创建消息队列
    struct mq_attr attr;
    attr.mq_maxmsg=10;
    attr.mq_msgsize=256;
    //打开消息队列
    mq=mq_open(mq_name,O_CREAT|O_RDWR,0644,&attr);
    if(mq==-1){
        perror("mq_open error");
        return -1;
    }
    //创建两个线程
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,thread1,NULL);
    pthread_create(&tid2,NULL,thread2,NULL);
    //等待线程结束
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    //关闭并删除消息队列
    mq_close(mq);
    mq_unlink(mq_name);
    return 0;
}
